#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "tableviewmodel.h"
#include "checkboxdelegate.h"
#include "btndelegate.h"
#include "switchdelegate.h"

#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    /// Init
    //必须要设置此项，否则样式表的hover无法生效
    ui->tableView->setMouseTracking(true);
    TableViewModel *pModel = new TableViewModel(this);
    ui->tableView->setModel(pModel);
    QStringList headers;
    headers << "" << "名称" << "启用禁用" << "操作";
    pModel->setHorizontalHeader(headers);
    // 加载数据、更新界面
    pModel->updateData({
                           {false, "小文", true},
                           {false, "小格", false},
                           {false, "小志", true},
                           {false, "小红", true},
                       });

    /// 勾选列代理
    TableHeaderView *pHeader = new TableHeaderView(Qt::Horizontal, ui->tableView, 0);
    ui->tableView->setHorizontalHeader(pHeader);
    CheckBoxDelegate *pDelegate = new CheckBoxDelegate(this, 0);
    ui->tableView->setItemDelegateForColumn(0, pDelegate);
    connect(pModel, SIGNAL(stateChanged(int)), pHeader, SLOT(onStateChanged(int)));
    connect(pHeader, SIGNAL(stateChanged(int)), pModel, SLOT(onStateChanged(int)));

    /// 操作列代理
    TableViewBtnDelegate *m_btnDelegate = new TableViewBtnDelegate(QStringList()<< "专业编辑" << "删除", this);
    ui->tableView->setItemDelegateForColumn(3, m_btnDelegate);
    // 连接信号槽，根据需要添加
    connect(m_btnDelegate, &TableViewBtnDelegate::oper, this, [=](const QModelIndex &index, QString oper){
       QMessageBox::information(this, "提示", QString("%2 第 %1 行数据").arg(index.row()+1).arg(oper));
    });

    /// 开关列代理
    SwitchDelegate *switchDelegate = new SwitchDelegate(this, 2);
    ui->tableView->setItemDelegateForColumn(2, switchDelegate);
    connect(switchDelegate, &SwitchDelegate::stateChanged, this, [=](const QModelIndex &index, bool state){
       QString ac = state ? "启用" : "禁用";
       QMessageBox::information(this, "提示", QString("%1 第 %2 行数据").arg(ac).arg(index.row()+1));
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}
